package huawei.js2025;

import java.util.Arrays;
import java.util.Scanner;

/**
 * 实力差距最小总和 - 动态规划
 */
public class Question21 {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int d = sc.nextInt();

        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = sc.nextInt();
        }

        int[] pars = new int[n]; // 前n个实力最多能匹配多少对
        int[] diff = new int[n]; // 前n个匹配上的实力差距和是多少

        // 排序
        Arrays.sort(arr);

        // 初始化
        if (arr[1] - arr[0] <= d) {
            pars[1] = 1;
            diff[1] = arr[1] - arr[0];
        }

        for (int i = 2; i < n; i++) {
            if (arr[i] - arr[i - 1] <= d) {
                if (pars[i-1] < pars[i - 2] + 1) {
                    pars[i] = pars[i - 2] + 1;
                    diff[i] = diff[i - 2] + arr[i] - arr[i - 1];
                }  else  {
                    if (arr[i] - arr[i - 1] < arr[i - 1] - arr[i - 2]) {
                        pars[i] = pars[i - 2] + 1;
                        diff[i] = diff[i - 2] + arr[i] - arr[i - 1];
                    } else {
                        pars[i] = pars[i - 1];
                        diff[i] = diff[i - 1];
                    }
                }
            } else {
                // 如果不是，直接 i-1 的结果
                pars[i] = pars[i - 1];
                diff[i] = diff[i - 1];
            }
        }

        if (pars[n - 1] == 0) {
            System.out.println(-1);
        } else {
            System.out.println(diff[n - 1]);
        }
    }
}
